import fs from "fs";
import path from "path";

// Interface for webpack configuration
interface WebpackConfig {
  output: {
    filename: string;
  };
}

// Get the pairs from webpack.config.js
const getWebpackPairs = () => {
  const webpackConfigPath = path.resolve(__dirname, "../webpack.config.js");
  // Dynamic import with eval to avoid require
  const webpackConfig = eval("require")(webpackConfigPath) as WebpackConfig[];

  // Extract the nodeId names from the webpack config
  const nodeIds = webpackConfig.map((config) =>
    path.basename(config.output.filename, ".js")
  );

  return nodeIds;
};

const createBundledConfig = async () => {
  const nodeIds = getWebpackPairs();
  const uiDistDir = path.resolve(__dirname, "../dist/ui");
  const bundledConfigDir = path.resolve(__dirname, "../dist/bundled-config");

  // Create bundled-config directory if it doesn't exist
  if (!fs.existsSync(bundledConfigDir)) {
    fs.mkdirSync(bundledConfigDir, { recursive: true });
  }

  // For each node ID, read the bundle and create a file that exports its contents
  for (const nodeId of nodeIds) {
    const bundlePath = path.join(uiDistDir, `${nodeId}.js`);

    if (fs.existsSync(bundlePath)) {
      const bundleContent = fs.readFileSync(bundlePath, "utf-8");
      const encodedContent = Buffer.from(bundleContent).toString("base64");

      // Use CommonJS exports with browser-compatible base64 decoding
      const exportFileContent = `
// This file is auto-generated by create-bundled-config.ts
const encodedContent = "${encodedContent}";
const content = typeof Buffer !== 'undefined' 
  ? Buffer.from(encodedContent, 'base64').toString('utf-8')
  : atob(encodedContent);

module.exports = content;
      `.trim();

      fs.writeFileSync(
        path.join(bundledConfigDir, `${nodeId}.js`),
        exportFileContent
      );

      // Create TypeScript definition file
      const dtsContent = `
declare const content: string;
export = content;
      `.trim();

      fs.writeFileSync(
        path.join(bundledConfigDir, `${nodeId}.d.ts`),
        dtsContent
      );
    } else {
      console.warn(`Bundle not found for ${nodeId} at ${bundlePath}`);
    }
  }

  // Create an index file to export all node bundle contents using CommonJS
  const indexPath = path.join(bundledConfigDir, "index.js");
  const indexExports = nodeIds
    .map((id) => `  ${id}: require('./${id}.js')`)
    .join(",\n");

  const indexContent = `
// This file is auto-generated by create-bundled-config.ts
module.exports = {
${indexExports}
};
  `.trim();

  fs.writeFileSync(indexPath, indexContent);

  console.log(`Created bundled config exports in ${bundledConfigDir}`);
};

createBundledConfig().catch((err) => {
  console.error("Error creating bundled config:", err);
  process.exit(1);
});
